/*
 * MathML Library
 * @author Sebastian Jaurena <seba.jaurena@gmail.com>
 */

var MathML = {

    math: null,
    elements: null,
    
    buttons: null,

    itemEdited: null,

    /**
     * Constructor
     */
    init: function() {

	MathML.elements = Elements;
	MathML.math = $('#math');
	MathML.math.append($('<math xmlns="http://www.w3.org/1998/Math/MathML"><mrow>?</mrow></math>'));
	
	$('mrow').live('click',function(){MathML.editable(this)});
	
	MathML.editor = $('#editor');
	MathML.editor.css({
	    left: $(document).width()/2 - MathML.editor.width()/2,
	    top: $(document).height()/2 - MathML.editor.height()/2 - 100
	});

	MathML.editor();
    },

    editor: function(){

	$('#editor input').live('click',function(){
	    MathML.change(this)
	});

	$.each(MathML.elements.operators,function(func,elem){
	    $('#operators').append(
		$('<input>').attr({
		    type: 'button',
		    name: func,
		    value: elem.label
		}).attr('class','operator')
	    );
	});
	
	$.each(MathML.elements.functions,function(func,elem){
	    $('#functions').append(
		$('<input>').attr({
		    type: 'button',
		    name: func,
		    value: elem.label
		}).attr('class','function')
	    );
	});
    },
    
    // Events
    editable: function(item) {
	MathML.itemEdited = item;
	MathML.editor.fadeIn('fast');
    },

    change: function(button) {
	
	$(MathML.itemEdited).replaceWith($(MathML.elements.functions[$(button).attr('name')].code));
	MathML.editor.fadeOut('fast');

	var content = $(MathML.math).html();
	$(MathML.math).html('');
	$(MathML.math).append($(content));
	MathML.itemEdited = null;
    }
}
